using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.ComponentModel;
using System.Data;
using ACME.Northwind.DataTransfer;
using ACME.Northwind.Business.Objects;
using Widgetsphere.Core.DataAccess;
using System.Linq.Expressions;
using ACME.Northwind.Business.LINQ;
using Widgetsphere.Core.Util;
using System.Reflection;

namespace ACME.Northwind.DataTransfer.Extensions
{
	public static partial class EmployeeTerritoryExtension
	{
		#region Fill DAL

		/// <summary>
		/// Populate a DAL object from its corresponding DTO.
		/// </summary>
		/// <param name="item">The empty DAL object.</param>
		/// <param name="dtoItem">The source DTO to load.</param>
		public static void Fill(this EmployeeTerritory item, EmployeeTerritoryDTO dtoItem)
		{
			if (dtoItem == null) throw new Exception("The EmployeeTerritory DTO cannot be null.");
			if (item == null) throw new Exception("The EmployeeTerritory item cannot be null.");
			DataRow dr = ((DataRow)((IWrappingClass)item).WrappedClass);
			dr["EmployeeID"] = dtoItem.EmployeeId;
			dr["TerritoryID"] = dtoItem.TerritoryId;
		}

		#endregion

		#region Fill DTO

		/// <summary>
		/// Populate a DTO object collection from its corresponding DAL object collection.
		/// </summary>
		/// <param name="list">The destination DTO collection.</param>
		/// <param name="employeeterritoryCollection">The source DAL collection.</param>
		public static void Fill(this List<EmployeeTerritoryDTO> list, EmployeeTerritoryCollection employeeterritoryCollection)
		{
			if (employeeterritoryCollection == null) throw new Exception("The EmployeeTerritory collection cannot be null.");
			if (list == null) list = new List<EmployeeTerritoryDTO>();
			foreach (EmployeeTerritory item in employeeterritoryCollection)
			{
				EmployeeTerritoryDTO newItem = new EmployeeTerritoryDTO();
				newItem.Fill(item);
				list.Add(newItem);
			}
		}

		/// <summary>
		/// Populate a DTO object from its corresponding DAL object.
		/// </summary>
		/// <param name="item">The source DAL object.</param>
		/// <param name="dtoItem">The empty DTO to load.</param>
		public static void Fill(this EmployeeTerritoryDTO dtoItem, EmployeeTerritory item)
		{
			if (dtoItem == null) throw new Exception("The EmployeeTerritory DTO cannot be null.");
			if (item == null) throw new Exception("The EmployeeTerritory item cannot be null.");
			dtoItem.TerritoryId = item.TerritoryId;
			dtoItem.EmployeeId = item.EmployeeId;
			dtoItem.CreatedDate = item.CreatedDate;
			dtoItem.CreatedBy = item.CreatedBy;
			dtoItem.ModifiedDate = item.ModifiedDate;
			dtoItem.ModifiedBy = item.ModifiedBy;
		}

		#endregion

		#region RunSelect

		/// <summary>
		/// Select all objects from store.
		/// </summary>
		public static void RunSelect(this List<EmployeeTerritoryDTO> list)
		{
			if (list == null) list = new List<EmployeeTerritoryDTO>();
			EmployeeTerritoryCollection retval = EmployeeTerritoryCollection.RunSelect();
			foreach (EmployeeTerritory item in retval)
			{
				EmployeeTerritoryDTO newItem = new EmployeeTerritoryDTO();
				newItem.Fill(item);
				list.Add(newItem);
			}
		}

		/// <summary>
		/// Using the specified Where expression, execute a query against the database to return a result set.
		/// </summary>
		public static void RunSelect(this List<EmployeeTerritoryDTO> list, Expression<Func<EmployeeTerritoryQuery, bool>> where)
		{
			if (list == null) list = new List<EmployeeTerritoryDTO>();
			list.Fill(EmployeeTerritoryCollection.RunSelect(where));
		}

		#endregion

		#region RunSelect Paged

		/// <summary>
		/// Using the specified Where expression, execute a query against the database to return a paged result set.
		/// </summary>
		public static PagedQueryResults<EmployeeTerritoryDTO> RunSelect(this List<EmployeeTerritoryDTO> list, string pageSize, string page, string sortOrder, string sortColumn, string linq)
		{
			if (list == null) list = new List<EmployeeTerritoryDTO>();
			#region Setup Variables and Error Check
			int po;
			int rpp;

			if (!int.TryParse(page, out po)) throw new Exception("The page number number is not a valid integer!");
			if (po < 1) po = 1;

			if (!int.TryParse(pageSize, out rpp)) throw new Exception("The page size is not a valid integer!");
			if (rpp < 1) rpp = 1;

			EmployeeTerritory.FieldNameConstants sortField;
			try
			{
				sortField = (EmployeeTerritory.FieldNameConstants)Enum.Parse(typeof(EmployeeTerritory.FieldNameConstants), sortColumn);
			}
			catch (Exception ex)
			{
				throw new Exception("The sort field is not valid!");
			}

			bool ascending = (sortOrder.ToLower() == "asc" || sortOrder.ToLower() == "ascending");
			#endregion

			PagedQueryResults<EmployeeTerritoryDTO> retVal = new PagedQueryResults<EmployeeTerritoryDTO>();
			EmployeeTerritoryPaging paging = new EmployeeTerritoryPaging();
			paging.RecordsperPage = rpp;
			paging.PageIndex = po;
			paging.OrderByList.Add(new EmployeeTerritoryPagingFieldItem(sortField, ascending));

			EmployeeTerritoryCollection dalList = null;
			if (string.IsNullOrEmpty(linq))
			{
				dalList = EmployeeTerritoryCollection.RunSelect(x => true, paging);
			}
			else
			{
				MethodInfo method = LINQDynamicCompile.GetLINQMethodPaged(linq, "ACME.Northwind.Business", "EmployeeTerritory");
				dalList = (EmployeeTerritoryCollection)method.Invoke(null, new object[] { paging });
			}

			if (list == null) list = new List<EmployeeTerritoryDTO>();
			foreach (EmployeeTerritory item in dalList)
			{
				EmployeeTerritoryDTO newItem = new EmployeeTerritoryDTO();
				newItem.Fill(item);
				list.Add(newItem);
			}

			retVal.CurrentPage = paging.PageIndex;
			double totalPages = Math.Ceiling((double)paging.RecordCount / (double)paging.RecordsperPage);
			retVal.TotalPages = (int)totalPages;
			retVal.TotalRecords = paging.RecordCount;
			retVal.GridData = list;

			return retVal;
		}

		#endregion

		#region RunSelect Paged

		/// <summary>
		/// Using the specified Where expression, execute a query against the database to return a result set.
		/// </summary>
		public static void RunSelect(this List<EmployeeTerritoryDTO> list, string linq)
		{
			if (list == null) list = new List<EmployeeTerritoryDTO>();

			EmployeeTerritoryCollection dalList = null;
			if (string.IsNullOrEmpty(linq))
			{
				dalList = EmployeeTerritoryCollection.RunSelect(x => true);
			}
			else
			{
				MethodInfo method = LINQDynamicCompile.GetLINQMethodAll(linq, "ACME.TestProj.Business", "EmployeeTerritory");
				dalList = (EmployeeTerritoryCollection)method.Invoke(null, new object[] { });
			}

			if (list == null) list = new List<EmployeeTerritoryDTO>();
			foreach (EmployeeTerritory item in dalList)
			{
				EmployeeTerritoryDTO newItem = new EmployeeTerritoryDTO();
				newItem.Fill(item);
				list.Add(newItem);
			}
		}

		#endregion

		#region Persist

		/// <summary>
		/// Persists this object to store.
		/// </summary>
		public static EmployeeTerritoryDTO Persist(this EmployeeTerritoryDTO employeeterritory)
		{
			if (employeeterritory == null) throw new Exception("The EmployeeTerritory DTO cannot be null.");
			//Find this object and if not exists, create a new one
			EmployeeTerritory newItem = ACME.Northwind.Business.Objects.EmployeeTerritory.SelectUsingPK(employeeterritory.EmployeeId, employeeterritory.TerritoryId);
			EmployeeTerritoryCollection employeeterritoryCollection = null;
			if (newItem == null)
			{
				employeeterritoryCollection = new EmployeeTerritoryCollection();
				newItem = employeeterritoryCollection.NewItem();
			}
			else
			{
				employeeterritoryCollection = newItem.ParentCollection;
			}	

			//Populate the DAL and perist
			newItem.Fill(employeeterritory);
			if (!newItem.IsParented) employeeterritoryCollection.AddItem(newItem);
			employeeterritoryCollection.Persist();

			//Re-populate the passed-in object from the DAL
			employeeterritory.Fill(newItem);
			return employeeterritory;
		}

		/// <summary>
		/// Persists this collection to store.
		/// </summary>
		public static bool Persist(this List<EmployeeTerritoryDTO> employeeterritoryList)
		{
			if (employeeterritoryList == null) throw new Exception("The EmployeeTerritory DTO list cannot be null.");
			//Get all objects from the database that match PK
			EmployeeTerritoryCollection employeeterritoryCollection = new EmployeeTerritoryCollection();
			System.Collections.ArrayList keyList = new System.Collections.ArrayList();
			foreach (EmployeeTerritoryDTO dto in employeeterritoryList)
			{
				keyList.Add(new EmployeeTerritoryPrimaryKey(dto.EmployeeId, dto.TerritoryId));
			}			
			employeeterritoryCollection.SubDomain.AddSelectCommand(new ACME.Northwind.Business.SelectCommands.EmployeeTerritorySelectByPks(keyList));
			employeeterritoryCollection.SubDomain.RunSelectCommands();

			//Now find and populate the objects for saving
			foreach (EmployeeTerritoryDTO dto in employeeterritoryList)
			{
				EmployeeTerritory employeeterritory = (from x in (IEnumerable<EmployeeTerritory>)employeeterritoryCollection
					where x.EmployeeId == dto.EmployeeId && x.TerritoryId == dto.TerritoryId
					select x).FirstOrDefault();

				if (employeeterritory == null) employeeterritory = employeeterritoryCollection.NewItem();
				employeeterritory.Fill(dto);
				if (!employeeterritory.IsParented) employeeterritoryCollection.AddItem(employeeterritory);
			}
			employeeterritoryCollection.Persist();

			//Re-populate the passed-in object from the DAL
			List<EmployeeTerritoryDTO> deletedList = new List<EmployeeTerritoryDTO>();
			foreach (EmployeeTerritoryDTO dto in employeeterritoryList)
			{
				EmployeeTerritory employeeterritory = (from x in (IEnumerable<EmployeeTerritory>)employeeterritoryCollection
					where x.EmployeeId == dto.EmployeeId && x.TerritoryId == dto.TerritoryId
					select x).FirstOrDefault();

				if (employeeterritory != null) dto.Fill(employeeterritory);
				else deletedList.Add(dto);
			}

			//Remove the items that are no longer there (if any)
			foreach (EmployeeTerritoryDTO dto in deletedList)
			{
				employeeterritoryList.Remove(dto);
			}

			return true;
		}

		#endregion

		#region EmployeeTerritory Select by Column

		#endregion

		#region EmployeeTerritory SelectUsingPK

		/// <summary>
		/// Select a single object from this collection by its primary key.
		/// </summary>
		public static void SelectUsingPK(this EmployeeTerritoryDTO employeeterritory, int employeeid, string territoryid)
		{
			EmployeeTerritory item = ACME.Northwind.Business.Objects.EmployeeTerritory.SelectUsingPK(employeeid, territoryid);
			employeeterritory.Fill(item);
		}

		#endregion

		#region EmployeeTerritory Select By Foreign Key

		/// <summary>
		/// Populate a 'Employee' DTO object collection from its relationship with the 'EmployeeTerritory' table.
		/// </summary>
		public static void SelectByEmployee(this List<EmployeeTerritoryDTO> EmployeeTerritoryList, int employeeid)
		{
			EmployeeTerritoryCollection list = EmployeeTerritoryCollection.RunSelect(x => x.EmployeeId == employeeid);
			foreach (EmployeeTerritory item in list)
			{
				EmployeeTerritoryDTO newItem = new EmployeeTerritoryDTO();
				newItem.Fill(item);
				EmployeeTerritoryList.Add(newItem);
			}
		}

		/// <summary>
		/// Populate a 'Territory' DTO object collection from its relationship with the 'EmployeeTerritory' table.
		/// </summary>
		public static void SelectByTerritory(this List<EmployeeTerritoryDTO> EmployeeTerritoryList, string territoryid)
		{
			EmployeeTerritoryCollection list = EmployeeTerritoryCollection.RunSelect(x => x.TerritoryId == territoryid);
			foreach (EmployeeTerritory item in list)
			{
				EmployeeTerritoryDTO newItem = new EmployeeTerritoryDTO();
				newItem.Fill(item);
				EmployeeTerritoryList.Add(newItem);
			}
		}

		#endregion

	}

}
